package ar.com.android.restoapp.forms;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import ar.com.android.restoapp.adapters.AutoCompleteFoodAcapter;
import ar.com.android.restoapp.adapters.ListViewOrderAdapter;
import ar.com.android.restoapp.adapters.SpinnerTypeFoodAdapter;
import ar.com.android.restoapp.dbHelpers.SQLFoodOrderHelper;
import ar.com.android.restoapp.entities.Food;
import ar.com.android.restoapp.entities.OrderItems;
import ar.com.android.restoapp.entities.TypeFood;
import ar.com.android.restoapp.providers.FoodProvider;
import ar.com.android.restoapp.providers.OrderItemDataSource;
import ar.com.android.restoapp.providers.TypeFoodProvider;
import ar.com.android.restoapp.utils.AppGlobalVariables;
import ar.com.android.restoapp.utils.Constants;

public class OrderActivity extends Activity {
	private static final String TAG = "OrderActivity";
	
	ListViewOrderAdapter listViewOrderAdapter;
	private List<OrderItems> lstOrder;
	private List<Food> foods = new ArrayList<Food>();
	Food selectedFood;
	Integer selectedTable;
	Integer selectedMenu;

	//	Defined Object Form and LogTag
	TextView tvUserCompleteName;
	TextView tvTable;
	Spinner spiTypeFood;
	AutoCompleteTextView actvDescription;
	EditText etQuantity;
	ImageButton butAdd;
	ImageButton butEdit;
	ImageButton butDelete;
	ListView lvOrder;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order);
        
        Bundle bundle = getIntent().getExtras();
        
        setTitle(getString(R.string.app_name) + " - " + getString(R.string.orderTitle));
        
		SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(this);
		sqlHelper.dbOpen();
		
        try {
			//Populate UserCompleteName
			tvUserCompleteName = (TextView) findViewById(R.id.lblUserName);
			tvUserCompleteName.setText(AppGlobalVariables.getInstance().getUserCompleteName());
			
			//Selected Previous Table and Menu 
			selectedTable =  bundle.getInt("selectedTable");
			selectedMenu = bundle.getInt("selectedMenu");
			
			tvTable = (TextView) findViewById(R.id.tvTable);
			tvTable.setText(tvTable.getText().toString() + " " + selectedTable);
			
			lvOrder = (ListView) findViewById(R.id.lvOrder);
			
			//Load Items of Order
			OrderItemDataSource orderItemDataSource = new OrderItemDataSource(OrderActivity.this);
			lstOrder = orderItemDataSource.getAllOrderItems(selectedTable);
			
			if(lstOrder == null)
				lstOrder = new ArrayList<OrderItems>();
			
			listViewOrderAdapter = new ListViewOrderAdapter(this, R.id.lvOrder, lstOrder);
			lvOrder.setAdapter(listViewOrderAdapter);
			lvOrder.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					
					for(OrderItems orderItem: lstOrder)
						orderItem.setSelected(false);
					
					lstOrder.get(position).setSelected(true);
					listViewOrderAdapter.notifyDataSetChanged();
				}
			});

            TextView tv = (TextView) findViewById(R.id.actvDescription);
            tv.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    return gestureDetector.onTouchEvent(event);
                }
            });
			 
			//Populate TypeFood on Spinner
			spiTypeFood = (Spinner) findViewById(R.id.spiType);
			
			TypeFoodProvider typeFoodDataSource = new TypeFoodProvider(this);
			typeFoodDataSource.dbOpen();
			List<TypeFood> lstTypeFood = new ArrayList<TypeFood>();
			lstTypeFood = typeFoodDataSource.getAllTypeFood(selectedMenu);
			typeFoodDataSource.dbClose();

			SpinnerTypeFoodAdapter adapter = new SpinnerTypeFoodAdapter(this, android.R.layout.simple_spinner_item, lstTypeFood);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spiTypeFood.setAdapter(adapter);
					
			spiTypeFood.setOnItemSelectedListener(new OnItemSelectedListener() {
				 @Override 
			    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { 
					try {
						actvDescription = (AutoCompleteTextView) findViewById(R.id.actvDescription);
			    		etQuantity = (EditText) findViewById(R.id.etQuantity);
			    		actvDescription.requestFocus();
			    		
			    		SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(OrderActivity.this);
			    		FoodProvider foodDataSource = new FoodProvider(OrderActivity.this);
			    		
			    		TypeFood typeFood = (TypeFood) parentView.getItemAtPosition(position);
						foods = foodDataSource.getAllFood(typeFood.getIdTypeFood());

						AutoCompleteFoodAcapter adapter = new AutoCompleteFoodAcapter(OrderActivity.this, R.id.actvDescription, foods);
			    		actvDescription.setAdapter(adapter);
			    		
			    		actvDescription.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
								selectedFood = (Food) parentView.getItemAtPosition(position);
							}
						});
			    		
			    		sqlHelper.dbClose();
			    		
			    		//Clear Form Object
			    		actvDescription.setText("");
			    		etQuantity.setText("");
			    		
					} catch (Exception e) {
						Log.e(TAG, e.getMessage());
					} 
			    }

				@Override
				public void onNothingSelected(AdapterView<?> parentView) {
				}
			});
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
        finally{
        	sqlHelper.dbClose();
        }
    }
    
	@Override  
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			menu.add(0, 1, 0, R.string.menuComments).setIcon(R.drawable.ic_comments);
		    return super.onCreateOptionsMenu(menu);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		Intent intentComment = new Intent(this, CommentsPopUpActivity.class);
		intentComment.putExtra("selectedTable", selectedTable);
		startActivityForResult(intentComment, 1);
		
		return true;
	}

    final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
        public boolean onDoubleTap(MotionEvent e) {
            openOptionsMenu();
            return true;
        }
    });
    
    public void onClickAdd(View v) throws Exception
    {
		SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(this);
		
    	if(actvDescription.getText().toString().equals("")) {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.msgInputProduct));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
    	}
    	else if(etQuantity.getText().toString().equals("")) {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.msgInputQuantity));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
    	}
    	else
    	{
    		sqlHelper.dbOpen();
    		
    		try
    		{
    			sqlHelper.beginTransaction();
    			
	    		OrderItemDataSource orderItemDataSource = new OrderItemDataSource(OrderActivity.this);
	    		
		    	OrderItems orderItem = new OrderItems();
		    	orderItem.setIdTable(selectedTable);
		    	orderItem.setOrderDescription(selectedFood.getDescription());
		    	orderItem.setIdFood(selectedFood.getIdFood());
		    	orderItem.setOrderQuantity(Double.parseDouble(etQuantity.getText().toString()));
		    	orderItem.setPrice(selectedFood.getPrice() * orderItem.getOrderQuantity());
		    	orderItem.setSelected(false);
		    	orderItem.setState(Constants.ORDER_ITEM_PENDING_SEND);
		    	
		    	long idOrderItem = orderItemDataSource.insertFood(orderItem);
		    	orderItem.setOrderItemId((int) idOrderItem);
		    	
		    	lstOrder.add(orderItem);
		    	listViewOrderAdapter.notifyDataSetChanged();
		    	
	    		//Clear Form Object
	    		actvDescription.setText("");
	    		etQuantity.setText("");
	    		actvDescription.requestFocus();
	    		
	    		sqlHelper.commitTransaction();
    		}
    		catch (Exception e) {
    			sqlHelper.rollbackTransaction();
				Log.e(TAG, e.toString());
			}
	    	finally {
	    		sqlHelper.dbClose();
	    	}
    		
    	}
    }
    
    public void OnClickEdit(View v) throws Exception
    {
    	SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(this);
    	
    	if(actvDescription.getText().toString().equals("")) {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.msgInputProduct));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
    	}
    	else if(etQuantity.getText().toString().equals("")) {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.msgInputQuantity));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
    	}
    	else
    	{
    		sqlHelper.dbOpen();
    		
    		try
    		{
	    		OrderItems orderItem = null;
	    		for(OrderItems orderItems: lstOrder)
	        	{
	        		if(orderItems.getSelected())
	        		{
	        			orderItem = orderItems;
	        			break;
	        		}
	        	}
	    		
	    		sqlHelper.beginTransaction();
	    		
	    		if(orderItem != null)
	    		{
	    			if(orderItem.getState().equals(Constants.ORDER_ITEM_SUBMITTED)) {
	    				LayoutInflater inflater = getLayoutInflater();
	    				View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

	    				TextView text = (TextView) layout.findViewById(R.id.text);
	    				text.setText(getText(R.string.msgEditProductDenied));

	    				Toast toast = new Toast(getApplicationContext());
	    				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	    				toast.setDuration(Toast.LENGTH_LONG);
	    				toast.setView(layout);
	    				toast.show();	    				
	    			}
	    			else {
			    		OrderItemDataSource orderItemDataSource = new OrderItemDataSource(OrderActivity.this);
			    		
				    	orderItem.setOrderDescription(selectedFood.getDescription());
				    	orderItem.setIdFood(selectedFood.getIdFood());
				    	orderItem.setOrderQuantity(Double.parseDouble(etQuantity.getText().toString()));
				    	orderItem.setPrice(selectedFood.getPrice() * orderItem.getOrderQuantity());
				    	orderItem.setSelected(true);
				    	orderItem.setState(Constants.ORDER_ITEM_PENDING_SEND);
				    	
				    	orderItemDataSource.updateOrderItem(orderItem);
				    	
				    	listViewOrderAdapter.notifyDataSetChanged();
	    			}
    			}
	    		//Clear Form Object
	    		actvDescription.setText("");
	    		etQuantity.setText("");
	    		actvDescription.requestFocus();
	    		
	    		sqlHelper.commitTransaction();
    		}
    		catch (Exception e) {
    			sqlHelper.rollbackTransaction();
    			Log.e(TAG, e.toString());
			}
    		finally{
    			sqlHelper.dbClose();
    		}
    	}
    }
    
    public void OnClickDelete(View v)
    {
    	for(OrderItems orderItems: lstOrder)
    	{
    		if(orderItems.getSelected())
    		{
    			SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(this);
    			sqlHelper.dbOpen();
    			try
    			{
    				OrderItemDataSource orderItemDataSource = new OrderItemDataSource(OrderActivity.this);
    				orderItemDataSource.removeOrderItem(orderItems.getOrderItemId());
	    		
    				lstOrder.remove(orderItems);
    				listViewOrderAdapter.notifyDataSetChanged();
    				
    			}
    			catch (Exception e) {
    				Log.e(TAG, e.toString());
				}
    			finally {
    				sqlHelper.dbClose();
    			}
    			break;
    		}
    	}
    }
}
